import originJSONP from 'jsonp'


/**
 * [jsonp description]
 * @param  {[type]} url    [原始地址]
 * @param  {[type]} data   [参数]
 * @param  {[type]} option [对应jsonp插件的option]
 * @return {[type]}        [Promise]
 */
export default function jsonp(url, data, option) {
    url += (url.indexOf('?') == -1 ? '?' : '&') + param(data);
    // url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

    return new Promise((resolve, reject) => {
        originJSONP(url, option, (err, data) => {
            if (!err) {
                resolve(data);
            } else {
                reject(err);
            }
        })
    })
}

/**
 * [param 拼接url参数]
 * @param  {[type]} data [参数的json格式]
 * @return {[type]}      [string]
 */
function param(data) {
    let url = '';
    for (var k in data) {
        let value = data[k] != undefined ? data[k] : '';
        url += `&${k}=${encodeURIComponent(value)}`
    }

    return url ? url.substring(1) : ''
}
